<?php

namespace addons\booking\model;

use think\Model;


class Cart extends Model
{

    // 表名
    protected $name = 'booking_goods_cart';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];


    protected static function init()
    {
    }

    public static function add($goods_id, $user_id, $sceneval)
    {
        $row = (new self)->where('goods_id', $goods_id)
            ->where('user_id', $user_id)
            ->where('sceneval', $sceneval)
            ->find();
        //已存在，数量加
        if ($row) {
            if ($sceneval == 2) {
                $row->sceneval = $sceneval;
                $row->nums = 1;
                $row->save();
            } else {
                $row->setInc('nums');
            }
        } else {
            $row = (new self);
            $row->save([
                'goods_id' => $goods_id,
                'user_id'  => $user_id,
                'sceneval' => $sceneval,
                'nums'     => 1
            ]);
        }
        return $row->id;
    }

    /**
     * 购物车列表
     *
     * @param array $param
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function tableList($user_id, $ids = '', $sceneval = 1)
    {
        $list = self::field('id,goods_id,nums,user_id,sceneval')->with([
            'Goods' => function ($query) {
                $query->field('id,name,image,price')->where('status', 'up')->where('stocks', '>', 0);
            }
        ])->where(function ($query) use ($user_id, $ids, $sceneval) {
            $query->where('user_id', $user_id);
            if ($ids) {
                $query->where('id', 'in', $ids);
            }
            $query->where('sceneval', $sceneval);
        })->order('createtime desc')->select();

        //没有商品过滤数据
        foreach ($list as $key => $item) {
            if (empty($item->goods)) {
                $item->delete();
                unset($list[$key]);
            }
        }

        return $list;
    }

    public function Goods()
    {
        return $this->hasOne('Goods', 'id', 'goods_id', [], 'LEFT');
    }
}
